"""
用户API
处理用户的CRUD操作
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity

from app.models.user import User, UserRole
from app.schemas.user import UserSchema
from app.extensions import db
from app.utils.auth import admin_required

user_bp = Blueprint('user', __name__)

@user_bp.route('/', methods=['GET'])
@jwt_required()
def get_users():
    """获取所有用户"""
    current_user_id = get_jwt_identity()
    current_user = User.query.get(current_user_id)
    
    # 只有管理员可以查看所有用户
    if not current_user or not current_user.is_admin():
        return jsonify({"error": "权限不足"}), 403
    
    users = User.query.all()
    result = []
    
    for user in users:
        result.append({
            "id": user.id,
            "username": user.username,
            "email": user.email,
            "role": user.role,
            "full_name": user.full_name,
            "is_active": user.is_active,
            "created_at": user.created_at.isoformat() if user.created_at else None
        })
    
    return jsonify(result), 200

@user_bp.route('/<int:user_id>', methods=['GET'])
@jwt_required()
def get_user(user_id):
    """获取单个用户"""
    current_user_id = get_jwt_identity()
    current_user = User.query.get(current_user_id)
    
    # 用户只能查看自己的信息，管理员可以查看所有人
    if not current_user.is_admin() and current_user_id != user_id:
        return jsonify({"error": "权限不足"}), 403
    
    user = User.query.get(user_id)
    
    if not user:
        return jsonify({"error": "用户不存在"}), 404
    
    return jsonify({
        "id": user.id,
        "username": user.username,
        "email": user.email,
        "role": user.role,
        "full_name": user.full_name,
        "is_active": user.is_active,
        "created_at": user.created_at.isoformat() if user.created_at else None
    }), 200

@user_bp.route('', methods=['POST'])
@jwt_required()
@admin_required
def create_user():
    """创建新用户"""
    data = request.get_json()
    
    if User.query.filter_by(username=data.get('username')).first():
        return jsonify({"msg": "用户名已存在"}), 400
    
    if User.query.filter_by(email=data.get('email')).first():
        return jsonify({"msg": "邮箱已存在"}), 400
    
    try:
        user = User(
            username=data.get('username'),
            email=data.get('email'),
            role=data.get('role', 'user')
        )
        user.set_password(data.get('password'))
        db.session.add(user)
        db.session.commit()
        
        return jsonify({
            "msg": "用户创建成功",
            "user": UserSchema().dump(user)
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"创建用户失败: {str(e)}"}), 500

@user_bp.route('/<int:user_id>', methods=['PUT'])
@jwt_required()
def update_user(user_id):
    """更新用户信息"""
    current_user_id = get_jwt_identity()
    user = User.query.get(user_id)
    
    if not user:
        return jsonify({"msg": "用户不存在"}), 404
    
    # 只允许管理员或用户本人更新用户信息
    current_user = User.query.get(current_user_id)
    if user_id != current_user_id and not current_user.is_admin:
        return jsonify({"msg": "无权限更新此用户信息"}), 403
    
    data = request.get_json()
    
    try:
        # 只有管理员可以更改角色
        if 'role' in data and current_user.is_admin:
            user.role = data.get('role')
        
        if 'email' in data:
            existing_user = User.query.filter_by(email=data.get('email')).first()
            if existing_user and existing_user.id != user_id:
                return jsonify({"msg": "邮箱已存在"}), 400
            user.email = data.get('email')
        
        db.session.commit()
        
        return jsonify({
            "msg": "用户信息更新成功",
            "user": UserSchema().dump(user)
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"更新用户失败: {str(e)}"}), 500

@user_bp.route('/<int:user_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def delete_user(user_id):
    """删除用户"""
    user = User.query.get(user_id)
    
    if not user:
        return jsonify({"msg": "用户不存在"}), 404
    
    try:
        db.session.delete(user)
        db.session.commit()
        return jsonify({"msg": "用户删除成功"}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"删除用户失败: {str(e)}"}), 500 